package webs.servlet.ServletDemoThree;
//通过表单、验证码进行登陆验证

import org.apache.commons.beanutils.BeanUtils;
import webs.servlet.ServletDemoOne.jdbcToolClass;
import webs.servlet.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

@WebServlet("/demo12")
public class servletTest_Twelve extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String str=servletCheckImg.str;
        //登陆验证
        if(!str.equals(req.getParameter("checkPassword")))
        {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer=resp.getWriter();
            writer.write("验证码错误！");
        }
        else
        {
            User loginUser = new User();
            Map parameterMap = req.getParameterMap();
            try
            {
                BeanUtils.populate(loginUser, parameterMap);
                if(dataCheck(loginUser.getUsername(), loginUser.getPassword()))
                {
                    resp.sendRedirect("Welcome.html");
                }
                else
                {
                    resp.setContentType("text/html;charset=utf-8");
                    PrintWriter writer=resp.getWriter();
                    writer.write("登录失败，用户名或密码错误！");
                }
            } catch (IllegalAccessException e)
            {
                e.printStackTrace();
            } catch (InvocationTargetException e)
            {
                e.printStackTrace();
            } catch (SQLException throwables)
            {
                throwables.printStackTrace();
            }
        }
    }
    public static boolean dataCheck(String username,String password) throws SQLException
    {
        String sql="SELECT * FROM account WHERE username=? AND password=?";
        Connection con= jdbcToolClass.Register();
        PreparedStatement preparedStatement=con.prepareStatement(sql);
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);
        ResultSet resultSet=preparedStatement.executeQuery();
        if(resultSet!=null)
        {
            jdbcToolClass.close(preparedStatement,con,resultSet);
            return true;
        }
        else
        {
            jdbcToolClass.close(preparedStatement, con, resultSet);
            return false;
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req,resp);
    }
}
